<script setup lang="ts">
import {
  addPatientApi,
  patientDetailApi,
  updatePatientApi,
} from "@/apis/patient";
import { onLoad } from "@dcloudio/uni-app";
import { ref } from "vue";
// 1. 表单数据
const formData = ref({
  name: "",
  idCard: "",
  gender: 1,
  defaultFlag: 1,
});
// 是否为默认就诊人
const onSwitchChange = (event: UniHelper.SwitchOnChangeEvent) => {
  formData.value.defaultFlag = event.detail.value === true ? 1 : 0;
};

// 2. 表单验证规则
const formRef = ref<UniHelper.UniFormsInstance>();
const formRules = {
  name: {
    rules: [
      { required: true, errorMessage: "请填写患者姓名" },
      {
        pattern: "^[\u4e00-\u9fa5]{2,5}$",
        errorMessage: "患者姓名为2-5位中文",
      },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: "请输入身份证号" },
      {
        pattern:
          "^[1-9]\\d{5}(?:18|19|20)\\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\\d|30|31)\\d{3}[\\dXx]$",
        errorMessage: "身份证号格式不正确",
      },
    ],
  },
  gender: {
    rules: [
      { required: true, errorMessage: "请勾选患者姓名" },
      {
        // 自定义校验
        validateFunction: (rule: any, value: any, data: any, callback: any) => {
          if (Number(formData.value.idCard.charAt(16)) % 2 !== value) {
            callback("性别与身份证号不匹配");
          }
          return true;
        },
      },
    ],
  },
};
const onSubmit = async () => {
  // 3. 表单校验
  try {
    await formRef.value?.validate?.();
    if (pageParams.id) {
      await updatePatientApi({
        ...formData.value,
        id: pageParams.id,
      });
    } else {
      // 提交表单数据给服务器，添加患者信息
      await addPatientApi(formData.value);
    }
    uni.showToast({ title: "保存成功", icon: "success" });
    // 跳转到患者列表页面
    uni.navigateBack();
  } catch (e) {
    console.log(e);
  }
};

const pageParams = defineProps<{ id: string }>();
const getDetail = async () => {
  const res = await patientDetailApi(pageParams.id);
  formData.value = {
    name: res.name,
    idCard: res.idCard,
    gender: res.gender || 0,
    defaultFlag: res.defaultFlag,
  };
};

if (pageParams.id) {
  uni.setNavigationBarTitle({ title: "编辑患者" });
  getDetail();
}
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms
        border
        label-width="220rpx"
        ref="formRef"
        :model="formData"
        :rules="formRules"
      >
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            v-model="formData.name"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            v-model="formData.idCard"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="name">
          <view class="uni-switch">
            <switch
              @change="onSwitchChange"
              :checked="formData.defaultFlag === 1"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
      <text>{{ formData }}</text>
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import "./index.scss";
</style>
